'use client';
import React, { useEffect, useState } from 'react';
import { getSesstion } from '@/lib/session';
import { useAppSelector } from '@/store/hooks';

// 自定义图标组件
const UploadOutlined = ({ className }: { className?: string }) => (
  <svg className={`w-6 h-6 ${className}`} fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
  </svg>
);

// 自定义消息提示组件
const Message = ({ type = 'info', content }: { type?: 'success' | 'error' | 'info'; content: string }) => {
  const bgColor = {
    success: 'bg-green-500',
    error: 'bg-red-500',
    info: 'bg-blue-500',
  };

  return (
    <div className={`fixed top-4 right-4 px-4 py-2 rounded-lg text-white shadow-lg ${bgColor[type]} z-50`}>
      {content}
    </div>
  );
};

type Props = {
  onChangeFile: (item: unknown) => void;
  isPlay: boolean;
};

const UploadFile: React.FC<Props> = ({ onChangeFile, isPlay }) => {
  const [isUploading, setIsUploading] = useState(false);
  const [message, setMessage] = useState<{ type: 'success' | 'error' | 'info'; content: string } | null>(null);
  const [fileInputKey, setFileInputKey] = useState(Date.now());

  // 显示消息提示
  const showMessage = (type: 'success' | 'error' | 'info', content: string) => {
    setMessage({ type, content });
    setTimeout(() => setMessage(null), 3000);
  };

  // 文件上传处理
  const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    setIsUploading(true);

    try {
      const formData = new FormData();
      formData.append('file', file);

      const response = await fetch('https://lizhan.fun/perf/session/upload', {
        method: 'POST',
        headers: {
          authorization: 'Bearer ' + getSesstion('token'),
        },
        body: formData,
      });

      if (!response.ok) {
        throw new Error('Upload failed');
      }

      const data = await response.json();
      showMessage('success', `${file.name} file uploaded successfully`);
      onChangeFile(data.data);
    } catch (error) {
      showMessage('error', `${file.name} file upload failed.`);
      console.error('Upload error:', error);
    } finally {
      setIsUploading(false);
    }
  };

  // 根据isPlay状态重置文件输入
  useEffect(() => {
    if (isPlay) {
      setFileInputKey(Date.now());
    }
  }, [isPlay]);

  return (
    <div className="flex items-center relative top-2 left-2">
      <label className="cursor-pointer">
        <input
          key={fileInputKey}
          type="file"
          onChange={handleFileChange}
          disabled={isUploading}
          className="hidden"
        />
        <UploadOutlined className="text-gray-700 hover:text-blue-500 transition-colors" />
      </label>
      {isUploading && (
        <div className="ml-2 text-sm text-gray-500">上传中...</div>
      )}
      {message && (
        <Message type={message.type} content={message.content} />
      )}
    </div>
  );
};

export default UploadFile;
